package com.sml.contorller;

import com.sml.pojo.Result;
import com.sml.pojo.User;
import com.sml.service.UserService;
import com.sml.utils.JwtUtil;
import com.sml.utils.MD5Util;
import com.sml.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated //参数校验注解
public class UserController {
    /**
     * 注入UserService
     */
    @Autowired
    private UserService userService;

    /**
     * 注入StringRedisTemplate
     */
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 注册
     *
     * @param username 用户名
     * @param password 密码
     * @return 响应注册结果
     */
    @PostMapping("/register")
    public Result<User> register(@Pattern(regexp = "^\\s{5,16}$") String username, @Pattern(regexp = "^\\s{5,16}$") String password) {

        //用户名是否被占用
        User user = userService.findByUsername(username);
        if (user != null) {
            return Result.error("用户名被占用");
        }
        //注册
        userService.register(username, password);
        return Result.success();
    }

    /**
     * 登录
     *
     * @param username 用户名
     * @param password 密码
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<String> login(@Pattern(regexp = "^\\S{5,16}$") String username, @Pattern(regexp = "^\\S{5,16}$") String password) {
        //用户名是否存在
        User user = userService.findByUsername(username);
        if (user != null && MD5Util.checkPassword(password, user.getPassword())) {
            Map<String, Object> claims = new HashMap<>();
            claims.put("username", user.getUsername());
            claims.put("id", user.getId());
            //登录成功---生成token，过期时间1小时
            String token = JwtUtil.genToken(claims);
            //将token存入redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            //设置过期时间 key，value，过期时间，时间单位
            //与登录成功的token的过期时间保持一致 1小时
            operations.set("token", token,1, TimeUnit.HOURS);
            return Result.success(token);
        }
        return Result.error("账户密码错误");
    }

    /**
     * 获取用户详细信息
     *
     * @return 用户信息
     */
    @GetMapping("/userInfo")
    public Result<User> userInfo() {
        Map<String, Object> claims = ThreadLocalUtil.get();
        //获取用户名
        String username = (String) claims.get("username");
        //根据用户名查询用户信息
        return Result.success(userService.findByUsername(username));
    }

    /**
     * 修改用户信息
     *
     * @param user 修改的用户信息
     * @return 修改结果
     */
    @PutMapping("/update")
    public Result<String> update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

    /**
     * 更新用户头像
     *
     * @param avatarUrl 头像地址
     * @return 响应更新结果
     */
    @PatchMapping("/updateAvatar")
    public Result<String> updateAvatar(@RequestParam @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     * 更新用户密码
     */
    @PatchMapping("/updatePwd")
    public Result<String> updatePwd(@RequestBody Map<String, Object> params) {

        //原密码
        String oldPwd = (String) params.get("old_pwd");
        //新密码
        String newPwd = (String) params.get("new_pwd");
        //确认密码
        String rePwd = (String) params.get("re_pwd");
        //参数校验--不为空判断
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)) {
            return Result.error("缺少必要参数");
        }
        //获取拦截器中的用户名
        Map<String, Object> claims = ThreadLocalUtil.get();
        String username = (String) claims.get("username");
        //参数校验--两次密码是否一致
        User user = userService.findByUsername(username);
        if (!MD5Util.checkPassword(oldPwd, user.getPassword())) {
            return Result.error("原密码错误");
        }
        //参数校验--新密码和确认密码是否一致
        if (!newPwd.equals(rePwd)) {
            return Result.error("两次填写新密码不一致");
        }
        //调用service完成密码更新
        userService.updatePwd(newPwd);
        return Result.success();
    }
}
